package com.xyh.transaction.service.imp;

import com.xyh.transaction.common.Current;
import com.xyh.transaction.entity.Address;
import com.xyh.transaction.exception.DeleteException;
import com.xyh.transaction.mapper.AddressMapper;
import com.xyh.transaction.mapper.OrderMapper;
import com.xyh.transaction.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void add(Address address) {
        Integer userId = Current.getCurrentUser().getUser().getId();

        if (address.getIsDefault() == 0) {
            addressMapper.updateDefaultByUserId(userId, 1);
        }

        address.setUserId(userId);
        address.setCreateBy(userId);
        address.setUpdateBy(userId);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());

        addressMapper.insert(address);

    }

    @Override
    public List<Address> getList() {
        return addressMapper.findByUserId(Current.getCurrentUser().getUser().getId());
    }

    @Override
    public void deleteAddress(Integer id) {
        if (orderMapper.findByAddressId(id) > 0) {
            throw new DeleteException("存在关联的订单，删除失败！");
        }
        ;
        addressMapper.deleteById(id);
    }

    @Override
    public void setDefaultAddress(Integer id) {
        Integer userId = Current.getCurrentUser().getUser().getId();
        addressMapper.updateDefaultByUserId(userId, 1);
        Address address = new Address();
        address.setId(id);
        address.setIsDefault(0);
        address.setUpdateTime(LocalDateTime.now());
        addressMapper.update(address);
    }

    @Override
    public void editAddress(Address address) {
        addressMapper.update(address);
    }
}
